_original_onselectstart = document.onselectstart 

function addListeners(){
    document.getElementById('drag').addEventListener('mousedown', mouseDown, true);
    window.addEventListener('mouseup', mouseUp, true);
    document.getElementById('textarea').addEventListener('change', saveText,true);
}

function saveText (e){
    alert('change fired');
}

function mouseUp(){
    document.onselectstart = _original_onselectstart;
    window.removeEventListener('mousemove', divMove, true);
    //store the divs x and y
}


function mouseDown(e){
    document.onselectstart = function () { return false; }
    window.addEventListener('mousemove', divMove, true);
}


function divMove(e){
  var div = document.getElementById('sticky');
  div.style.position = 'absolute';
  var x=document.body.scrollLeft+e.clientX
  var y=document.body.scrollTop+e.clientY
  
  if (x<0)      
      div.style.left = '0px';
  else
      div.style.left = x + 'px';
  if (y<0)      
      div.style.top = '0px';
  else
      div.style.top = y + 'px';  
}


function onText() {
    var sticky_dom = document.createElement('div');
    sticky_dom.className="sticky-main";
    sticky_dom.id="sticky";
        sticky_dom.innerHTML='<div class="sticky-tittle">\
        <div id="drag" onselectstart="return false" style="width:20px; background-color:red; float: left">X</div >\
        <div style="text-align:center"> Sticky Note</div>\
        </div>\
        <label class="sticky-label">\
        <textarea id="textarea" class="sticky-body" placeholder="start editing the sticky note"></textarea>\
        </label>';
    document.body.parentElement.insertBefore(sticky_dom, document.body);
};


onText();
addListeners();

